package com.example.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

/**
 * Quartz 任务类
 *
 * @author ding
 * @since 2024/7/15
 */
@PersistJobDataAfterExecution   //禁止每次调用时都创建一个新的jobDataMap
@DisallowConcurrentExecution    //禁止并发执行多个相同定义的JobDetail
//@Component
@Slf4j
public class MyJob implements Job {

    @Autowired
    private Scheduled scheduled;

    /**
     * 重写任务执行的方法
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //从context对象中获取jobDetail对象
        JobDetail jobDetail = context.getJobDetail();
        //从jobDetail对象中获取任务名称
        String jobName = jobDetail.getKey().getName();
        //从jobDetail对象中获取jobDataMap(存放共享数据的map集合)
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        //从jobDataMap中获取当前任务执行的次数
        Integer count = (Integer)jobDataMap.get("count");
        //输出当前任务相关信息
        log.info("任务{}第{}执行",jobName,count);
        String dataFormat = "yyyy-MM-dd HH:mm:ss";
        log.info("本次执行时间:{}", new SimpleDateFormat(dataFormat).format(context.getFireTime()));
        //更新共享数据
        jobDataMap.put("count", count++);
    }
}
